package com.lemon.smartsafetynew.ui.fragment.record;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.RefreshType;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafetynew.entity.common.CommonBo;
import com.lemon.smartsafetynew.entity.event.common.DataEvent;
import com.lemon.smartsafetynew.ui.activity.hidden.SafeHiddenDangerSearchActivity;
import com.lemon.smartsafetynew.ui.fragment.base.BaseSearchPullToRefreshFragment;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafetynew.entity.event.common.ViewEvent;
import com.lemon.smartsafetynew.entity.me.MeCompanyVo;
import com.lemon.smartsafetynew.entity.record.GridInfoDo;
import com.lemon.smartsafetynew.net.services.RecordServices;
import com.lemon.smartsafetynew.ui.activity.record.RecordFunctionActivity;
import com.lemon.smartsafetynew.ui.adapter.me.MeCompanyListAdapter;
import com.lemon.smartsafetynew.ui.adapter.record.RecordCompanyListAdapter;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.constants.SafeCloudConstants;
import com.lemon.smartsafetynew.util.record.RecordUtils;
import com.lemon.smartsafetynew.util.user.AccountUtil;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import kale.adapter.LemonRcvAdapter;

/**
 * 企业列表
 * Created by Andrew on 2017/10/21.
 */

public class CompanyListFragment extends BaseSearchPullToRefreshFragment<MeCompanyVo, List<MeCompanyVo>>
        implements RecyclerTClickListener<MeCompanyVo>, View.OnClickListener {

    private static final String gridId = "";
    private String search_params = "";
    private String businessType = "";
    private GridInfoDo gridInfoDo = null;
    private Gson gson = new Gson();

    private List<MeCompanyVo> historyList = new ArrayList<>();
    private RecordCompanyListAdapter recordCompanyListAdapter;

    @Override
    protected void getBaseArguments() {
        super.getBaseArguments();

        Bundle bundle = getArguments();

        if (bundle != null) {

            if (bundle.containsKey(KeyConstants.KEY_GRID_DO)) {
                gridInfoDo = (GridInfoDo) bundle.getSerializable(KeyConstants.KEY_GRID_DO);
            }

            if (bundle.containsKey(KeyConstants.KEY_BUSINESS_TYPE)) {
                businessType = (String) bundle.getSerializable(KeyConstants.KEY_BUSINESS_TYPE);
            }
        }
    }

    public static CompanyListFragment newInstance() {

        Bundle args = new Bundle();

        CompanyListFragment fragment = new CompanyListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static CompanyListFragment newInstance(String type) {

        Bundle args = new Bundle();
        args.putString(KeyConstants.KEY_BUSINESS_TYPE, type);

        CompanyListFragment fragment = new CompanyListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static CompanyListFragment newInstance(GridInfoDo infoDo) {

        Bundle args = new Bundle();
        args.putSerializable(KeyConstants.KEY_GRID_DO, infoDo);

        CompanyListFragment fragment = new CompanyListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onPullRefresh() {

        recyclerView.setVisibility(View.GONE);
        emptyImage.setVisibility(View.GONE);
        mMultiStateView.setVisibility(View.VISIBLE);

        LemonRequestParams params = new LemonRequestParams("");
        params.put("company_code", "");
        params.put("company_name", search_params);
        params.put("grid_id", gridInfoDo == null ? gridId : gridInfoDo.getGrid_id());
        params.put("status", "");
        params.put("pageNum", currentPage);
        params.put("pageSize", pageSize);

        RecordServices
                .init()
                .getCompanyList(RefreshType.REFRESH, params);
    }

    @Override
    public void onLoadMore() {

        recyclerView.setVisibility(View.GONE);
        emptyImage.setVisibility(View.GONE);
        mMultiStateView.setVisibility(View.VISIBLE);

        LemonRequestParams params = new LemonRequestParams("");
        params.put("company_code", "");
        params.put("company_name", search_params);
        params.put("grid_id", gridInfoDo == null ? gridId : gridInfoDo.getGrid_id());
        params.put("status", "");
        params.put("pageNum", currentPage);
        params.put("pageSize", pageSize);

        RecordServices
                .init()
                .getCompanyList(RefreshType.LOAD_MORE, params);
    }

    @Override
    public boolean goRefreshOnCreate() {
        return gridInfoDo != null;
    }

    @Override
    public LemonRcvAdapter<MeCompanyVo> getLemonAdapter() {
        return new MeCompanyListAdapter(mDataList, this,false);
    }

    @Override
    public String getHttpTag() {
        return KeyConstants.URL_SEARCH_COMPANY_BY_NAME;
    }

    @Override
    public void onItemClick(MeCompanyVo data, int position) {

        saveSearchHistory(data);

        if (CommonBo.BusinessType.HIDDEN_JUMP_SEARCH.getValue().equals(businessType)) {
            AppService.getBus().post(new DataEvent<MeCompanyVo>(data, CompanyListFragment.class.getName()));
            AppManager.getAppManager().finishActivity(SafeHiddenDangerSearchActivity.class);
        } else {
            Bundle bundle = new Bundle();
            bundle.putSerializable(KeyConstants.KEY_COMPANY_VO, data);
            UIHelper.showActivity(getmContext(), bundle, RecordFunctionActivity.class);
        }

    }

    @Subscribe
    public void onViewEvent(ViewEvent event) {
        if (RecordCompanyListAdapter.class.getName().equals(event.getTag())) {
            RecordUtils.removeCompanySearchHistory(AccountUtil.getUserID(), (gridInfoDo == null ? gridId : gridInfoDo.getGrid_id()));
            getSearchHistory();
        }
    }

    @Override
    protected void initViews() {
        super.initViews();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getmContext(), LinearLayoutManager.VERTICAL, false);
        recordCompanyListAdapter = new RecordCompanyListAdapter(historyList, this);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(recordCompanyListAdapter);

        txtClearn.setOnClickListener(this);
        lineRight.setOnClickListener(this);
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == KeyEvent.ACTION_DOWN || actionId == EditorInfo.IME_ACTION_DONE) {

                    search_params = editText.getText().toString().trim();
                    query(false);

                }
                return true;
            }
        });

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                search_params = s.toString().trim();

                query(true);

                if (!"".equals(s.toString())) {
                    txtClearn.setVisibility(View.VISIBLE);
                } else {
                    txtClearn.setVisibility(View.GONE);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        if (gridInfoDo == null) {
            // 获取历史搜索记录
            getSearchHistory();
            gridNameTv.setVisibility(View.GONE);
        } else {
            gridNameTv.setVisibility(View.VISIBLE);
            gridNameTv.setText(gridInfoDo.getGrid_name());
        }

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.lineRight:
                //点击搜索按钮
                search_params = editText.getText().toString().trim();
                query(false);
                break;

            case R.id.txtClearn:
                editText.getText().clear();
                break;

            default:
                break;
        }
    }

    /**
     * 搜索
     * 网格点信息    ==Null
     * gridInfoDo---------->  在输入搜索关键字时，输入数据为空串则显示历史，不为空搜索关键词
     * |
     * | != Null
     * |
     * \|/
     * *
     * 当点击搜索按钮后搜索
     */
    private void query(boolean realTime) {

        if (gridInfoDo == null) {

            // 企业搜索
            if (!realTime) {
                if ("".equals(search_params)) {
                    // 当搜索内容为空时，显示历史纪录
                    getSearchHistory();
                } else {
                    // 获取刷新
                    doPullRefresh();
                }
            } else {
                if ("".equals(search_params)) {
                    // 当搜索内容为空时，显示历史纪录
                    getSearchHistory();
                }
            }

        } else {
            // 网格点 ---> 企业搜索
            if (!realTime) {
                // 获取刷新
                doPullRefresh();
            } else {
                if ("".equals(search_params)) {
                    // 当搜索内容为空时，显示搜索一次全部列表
                    doPullRefresh();
                }
            }
        }
    }

    /**
     * 获取企业搜索历史记录
     */
    private void getSearchHistory() {

        String history = RecordUtils.getCompanySearchHistory(AccountUtil.getUserID(),
                (gridInfoDo == null ? gridId : gridInfoDo.getGrid_id()));


        if (history != null) {

            mMultiStateView.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            emptyImage.setVisibility(View.GONE);

            List<MeCompanyVo> companyVos;
            companyVos = gson.fromJson(history, new TypeToken<List<MeCompanyVo>>() {
            }.getType());

            MeCompanyVo companyVo = new MeCompanyVo();
            companyVo.setView_type(SafeCloudConstants.VIEW_TYPE);
            companyVo.setCompany_name(SafeCloudConstants.HISTORY_NAME);

            historyList.clear();
            historyList.addAll(companyVos);
            historyList.add(0, companyVo);
            recordCompanyListAdapter.notifyDataSetChanged();

        } else {

            mMultiStateView.setVisibility(View.GONE);
            recyclerView.setVisibility(View.GONE);
            emptyImage.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 保存企业搜索记录
     *
     * @param companyVo
     */
    private void saveSearchHistory(MeCompanyVo companyVo) {

        String history = RecordUtils.getCompanySearchHistory(AccountUtil.getUserID(),
                (gridInfoDo == null ? gridId : gridInfoDo.getGrid_id()));

        List<MeCompanyVo> companyVos = new ArrayList<>();

        if (history != null) {

            companyVos = gson.fromJson(history, new TypeToken<List<MeCompanyVo>>() {
            }.getType());

            if (!companyVos.contains(companyVo)) {
                // 本次搜索记录为不存在，就保存

                if (companyVos.size() >= Constants.HISTORY_MAX_NUMBER) {
                    //当companyVos为最大值20时，删除第一个再添加
                    int count = companyVos.size() - Constants.HISTORY_MAX_NUMBER;
                    for (int i = 0; i <= count; i++) {
                        companyVos.remove(companyVos.size() - 1);
                    }
                    companyVos.add(0, companyVo);
                } else {
                    companyVos.add(0, companyVo);
                }
                RecordUtils.saveCompanySearchHistory(AccountUtil.getUserID(),
                        (gridInfoDo == null ? gridId : gridInfoDo.getGrid_id()),
                        gson.toJson(companyVos));
            }

        } else {
            // 本地历史为空时，直接保存搜索记录
            companyVos.add(companyVo);
            RecordUtils.saveCompanySearchHistory(AccountUtil.getUserID(),
                    (gridInfoDo == null ? gridId : gridInfoDo.getGrid_id()),
                    gson.toJson(companyVos));
        }
    }

}
